package com.zhangkunhao.notes.web.filter;

import com.alibaba.fastjson.JSON;
import com.zhangkunhao.notes.entity.Do.User;
import com.zhangkunhao.notes.entity.bo.Message;
import com.zhangkunhao.notes.service.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户封禁权限的拦截器
 *
 * @author 20642
 */
@WebFilter("/*")
public class UserActivationStatusFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //获取当前访问的url
        String url = ((HttpServletRequest) request).getRequestURL().toString();

        //判断是否是登录或者忘记密码的请求
        if ((!url.contains("/user/login")) && (!url.contains("/user/forgetPassword"))) {
            //如果不是，则放行
            chain.doFilter(request, response);
            return;
        }

        //接收数据
        String email = request.getParameter("email");
        //封装返回的对象
        Message<User> message = new Message<>(null, "输入的邮箱错误，无法进入主页", 0);

        //用户是否被封禁，0表示被封禁，1表示未被封禁
        int activationStatus = 0;
        //调用service层
        List<User> users = new UserServiceImpl().selectAll().stream()
                .filter(user -> user.getEmail().equals(email))
                .collect(Collectors.toList());

        //判断是否存在该用户
        if (!users.isEmpty()) {
            //存在
            activationStatus = users.get(0).getActivationStatus();
        } else {
            // 不存在, 转换为json数据，写数据
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(message));

            return;
        }
        //是否被封禁
        if (activationStatus == 1) {
            //放行
            chain.doFilter(request, response);
        } else if (activationStatus == 0) {
            message.setResult("该用户已经被封禁，无法正常登录");
            // 转换为json数据，写数据
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(message));
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

}
